package core;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Component;

import dao.Serverinfo;
import dao.ServerinfoDAO;

@Component
public class EmailUtil {
	public void sendEmail(ServerinfoDAO serverInfoDao, String mail_to,String mail_title,String mail_content,String mail_content_title) {
		Serverinfo serverTab=(Serverinfo) serverInfoDao.findAll().get(0);
		String ServerEmail=serverTab.getServerEmail();
		String host = "smtp."+ServerEmail.split("\\.")[0].split("@")[1]+".com";
		String serverAccount=ServerEmail.split("@")[0];
		String ServerPwd=serverTab.getServerEmailPwd();

		String mail_head_name = "乐控科技注册验证邮件";

		String mail_head_value = "this is head of this mail";

		String mail_from = ServerEmail;
		
		String personalName = "乐控科技";
		try {
			Properties props = new Properties();// 获取系统环境
			Authenticator auth = new Email_Autherticator(serverAccount,ServerPwd);// 进行邮件服务用户认证
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			
			Session session = Session.getDefaultInstance(props, auth);
			// 设置session,和邮件服务器进行通讯
			MimeMessage message = new MimeMessage(session);
			message.setSubject(mail_title);// 设置邮件主题
//			message.setText(mail_content);// 设置邮件内容
			mail_content="<h4>"+mail_content_title+"</h4><body> " +  mail_content+"</body>";
			message.setContent(mail_content, "text/html;charset=UTF-8");// 设置邮件格式
			message.setHeader(mail_head_name, mail_head_value);// 设置邮件标题
			message.setSentDate(new Date());// 设置邮件发送时期
			Address address = new InternetAddress(mail_from, personalName);
			message.setFrom(address);// 设置邮件发送者的地址
			Address toaddress = new InternetAddress(mail_to);// 设置邮件接收者的地址
			message.addRecipient(Message.RecipientType.TO, toaddress);
			
			Transport.send(message);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
